package com.toponed.event;

import com.toponed.Application;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class BeginEvent extends MouseAdapter implements Runnable {

    boolean isBegin = false;
    JButton[] jbs;
    int x = 3, y = 3, i = 0, j = 1;

    public BeginEvent(boolean isBegin, int x, int y, JButton[] jbs) {
        this.isBegin = isBegin;
        this.x = x;
        this.y = y;
        this.jbs = jbs;
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        if (!isBegin) {
            new Thread(this).start();
        } else {
            JOptionPane.showMessageDialog(Application.window, " 已经开始了就不用再点了 ", " 恶意提示", JOptionPane.ERROR_MESSAGE);
        }
    }


    @Override
    public void run() {
        isBegin = true;
        int k = 0, round = (int) (120 + Math.random() * 10);
        while (k++ < round) {
            int last = i == 0 ? 0 : i;
            if (i < x) {
                i++;
            } else if (i == x * j && j < y) {
                j++;
                i = i + x;
            } else if (i > x * (y - 1) + 1 && i <= x * y) {
                i--;
            } else if (i == 1 + x * (j - 1) && j >= 1) {
                i -= x;
                j--;
            }
            jbs[i - 1].setBackground(Color.RED);
            if (last != 0) {
                jbs[last - 1].setBackground(Color.WHITE);
            }
            try {
                //第一部分为加速圈 10圈   加速圈过后是平衡圈 由默认指定， 后20圈是减速圈，  最后2圈为出结果圈
                long l = (k < round - 10) ? 300 - k * 20L : (k != round - 1) ? (k != round - 2) ? (20 - round + k) * 5L : 400L : 800L;
                Thread.sleep(l < 30 ? 30 : l);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
        }
        isBegin = false;
    }
}
